package com.mmall.concurrency.unsafeClass;

import com.mmall.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@NotThreadSafe
public class SimpleDateFormatUnsafe {
    public static int clientTotal = 5000;
    public static int threadTotal = 200;
    //定义在下面局部方法里面就正常了
    // public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    public static Date date;
    public static void main(String[] args) throws Exception{
        // 定义线程池和信号量
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i< clientTotal; i++){
            executorService.execute( () -> {
                // 线程里执行，加解锁，中间执行
                try {
                    semaphore.acquire();
                    date = dateCall();
                    semaphore.release();
                }catch (Exception e){
                    log.error("信号量捕获异常 ");
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            } );
        } // for
        log.info("日期{}",date);
        countDownLatch.await();
        executorService.shutdown();

    }

    public static Date dateCall(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            date = simpleDateFormat.parse("20180903");
        } catch (ParseException e) {
            log.info("解析日期异常");
            e.printStackTrace();
        }
        return date;
    }
}
